//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections;
using System.IO;
using System.Xml;
using CommunityServer.Components;
using CommunityServer.Configuration;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// Summary description for RebuildThumbnailsJob.
	/// </summary>
	public class RebuildThumbnailsJob : IJob
	{
		public RebuildThumbnailsJob() { }

		public void Execute(XmlNode node)
		{
			Queue queue = CSCache.Get("RebuildItems") as Queue;
			int items;

			if((queue != null) && (queue.Count > 0))
			{
				// Get how many items to process
				try { items = int.Parse(node.Attributes["picturesPerRun"].Value); }
				catch { items = 25; }

				// See if limiting items is 0 or less (do all of them)
				if(items <= 0)
					items = queue.Count;

				for(int i = ((queue.Count < items) ? queue.Count : items) - 1 ; i >= 0 ; i--)
				{
					RebuildItem item = queue.Dequeue() as RebuildItem;

					// The file may have already been regenerated, skip it
					if(File.Exists(item.Filename))
						continue;

					// If no settings, continue
					if(item.Settings == null)
						continue;

					//be sure to preserve the aspect ratio
					ImageHandling.GetMaintainedRatio(item.GalleryPost, item.Settings);

					// Generate the image
					ImageHandling.ScalePicture(item.Filename, item.GalleryPost, item.Settings);
				}

				// If the queue is empty, then remove it
				if(queue.Count <= 0)
					CSCache.Remove("RebuildItems");
			}
		}
	}
}
